package com.cloud.manager.web.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloud.manager.core.result.Result;
import com.cloud.manager.core.result.ResultCreator;
import com.cloud.manager.utils.Md5Utils;
import com.cloud.manager.utils.StringUtils;
import com.cloud.manager.web.body.LoginBody;
import com.cloud.manager.web.domain.User;
import com.cloud.manager.web.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 描述：
 *
 * @author FineEx   2021/11/18
 * @version 1.0
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {
    @Resource
    private UserService userService;

    @ApiOperation(value = "用户列表")
    @GetMapping("/all")
    public Result<Page<User>> userAll(int currentPage, int pageSize) {
        Page<User> users = userService.selectUserAll(currentPage, pageSize);
        return ResultCreator.success(users);
    }

    @ApiOperation(value = "新增用户")
    @PostMapping("/add")
    public Result<String> addUser(String userName, String password) {
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            return ResultCreator.fail("账号或密码为空！");
        }
        User user = new User();
        user.setUsername(userName);
        user.setPassword(Md5Utils.hash(password));
        userService.addUser(user);
        return ResultCreator.success("添加成功！");
    }

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Result<User> login(@RequestBody LoginBody body) {
        if (body == null
                || StringUtils.isEmpty(body.getUserName())
                || StringUtils.isEmpty(body.getPassword())) {
            return ResultCreator.fail("账号或密码为空！");
        }
        String userName = body.getUserName();
        String password = body.getPassword();
        User user = userService.login(userName, password);
        return ResultCreator.success(user);
    }

    @ApiOperation(value = "禁用用户")
    @PostMapping("/disable")
    public Result<String> disableUser(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return ResultCreator.fail("用户ID为空！");
        }
        if (userService.disableUser(userId) <= 0) {
            return ResultCreator.fail("禁用失败！");
        }
        return ResultCreator.success("禁用成功！");
    }
}
